<?php

namespace app\admin\controller\admin;

use app\admin\annotation\common\Auth;
use app\admin\controller\Admin;
use app\admin\model\admin\Log as LogModel;
use app\admin\validate\admin\Log as LogValidate;
use app\common\Constants;
use think\App;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log as ThinkLog;

class Log extends BaseLog
{
    public function __construct(
        App                $app,
        protected LogModel $logModel,
    )
    {
        parent::__construct($app, $logModel);
    }

    #[Auth('admin:log:clean')]
    public function clean(): \think\response\Json
    {
        try {
            $date = $this->request->post('date');
            // 无提交日期参数，则全部清除日志
            if (empty($date)) {
                $this->logModel->truncateTable();
                return $this->success();
            }
            // 提交清除截至日期，则检查日期格式
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                throw new ValidateException(Constants::E_COMMON_INVALID_PARAM);
            }
            // 按照截至日期清除日期数据
            $count = Db::name('admin_log')->whereTime('create_time', '<', $date)->delete(true);
            // 清除完成
            return $this->success(['data' => $count]);
        } catch (\Exception $e) {
            throw $e;
        }
    }
}